package com.westa.smallshop.goodssearch;

import android.support.annotation.NonNull;

import com.alibaba.fastjson.JSONObject;
import com.westa.smallshop.data.GoodsItem;
import com.westa.smallshop.data.source.GoodsItemDataSource;
import com.westa.smallshop.data.source.remote.BaseDataSource;

import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by cy on 10/11/16.
 */

class GoodsSearchPresenter implements GoodsSearchContract.Presenter, BaseDataSource.GetListCallBack<GoodsItem> {

    @NonNull
    private final GoodsSearchContract.View<GoodsItem> mMessageView;

    @NonNull
    private final GoodsItemDataSource mGoodsItemDataSource;

    GoodsSearchPresenter(@NonNull GoodsSearchContract.View<GoodsItem> goodsItemView,
                         @NonNull GoodsItemDataSource goodsItemDataSource) {
        mGoodsItemDataSource = checkNotNull(goodsItemDataSource);
        mMessageView = checkNotNull(goodsItemView);

        mMessageView.setPresenter(this);
    }

    @Override
    public void searchGoods(String keyword) {
        mGoodsItemDataSource.searchGoods(keyword, new BaseDataSource.LoadListCallBack<GoodsItem>() {
            @Override
            public void onRefreshDataSuccessful(List<GoodsItem> data) {
                mMessageView.setRefreshing(false);
                mMessageView.refreshData(data);
            }

            @Override
            public void onLoadMoreDataSuccessful(List<GoodsItem> data) {

            }

            @Override
            public void onLoadDataFailed() {
                mMessageView.setRefreshing(false);
                mMessageView.setEmptyViewVisibility(true);
            }
        });
    }

    @Override
    public void start() {
    }

    @Override
    public void destroy() {
        mGoodsItemDataSource.cancelLoadRequest();

    }

    @Override
    public void onGetDataSuccessful(List<GoodsItem> data) {

        if (mMessageView.isActive()) {
            mMessageView.setRefreshing(false);
            mMessageView.refreshData(data);
            mMessageView.setEmptyViewVisibility(false);
        }
    }

    @Override
    public void onGetDataFailed() {
        mGoodsItemDataSource.cancelLoadRequest();
    }
}
